# -*- coding: utf-8 -*-
"""
One-line Python HTTP Server
"""
import os
import signal
import sys
from functools import partial
from http import server


def test(HandlerClass=server.BaseHTTPRequestHandler,
         ServerClass=server.ThreadingHTTPServer,
         protocol="HTTP/1.0", port=80, bind=""):
    """Test the HTTP request handler class.

    This runs an HTTP server on port 8000 (or the port argument).

    """
    server_address = (bind, port)

    HandlerClass.protocol_version = protocol
    with ServerClass(server_address, HandlerClass) as httpd:
        sa = httpd.socket.getsockname()
        serve_message = "[%6d] Serving HTTP on {host} port {port} (http://{host}:{port}/) ..." % os.getpid()
        print(serve_message.format(host=sa[0], port=sa[1]))
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nKeyboard interrupt received, exiting.")
            sys.exit(0)


if __name__ == '__main__':
    pid_file = os.path.join(os.getenv('TEMP'), 'pyhttpd.pid')
    with open(pid_file, 'r') as pfile:
        lines = pfile.readlines()
        if lines is not None and len(lines) > 0:
            for pid in lines:
                try:
                    os.kill(int(pid), 9) # SIGKILL
                    print("Found a process with pid: %s, killed!" % pid)
                except Exception as e:
                    pass
        pfile.close()
    with open(pid_file, mode='w') as pfile:
        pfile.write(str(os.getpid()))
        pfile.close()
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('--cgi', action='store_true',
                        help='Run as CGI Server')
    parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
                        help='Specify alternate bind address '
                             '[default: all interfaces]')
    parser.add_argument('--directory', '-d', default=os.getcwd(),
                        help='Specify alternative directory '
                             '[default:current directory]')
    parser.add_argument('port', action='store',
                        default=80, type=int,
                        nargs='?',
                        help='Specify alternate port [default: 80]')
    args = parser.parse_args()
    if args.cgi:
        handler_class = server.CGIHTTPRequestHandler
    else:
        handler_class = partial(server.SimpleHTTPRequestHandler,
                                directory=args.directory)
    test(HandlerClass=handler_class, port=args.port, bind=args.bind)
